package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.exception.BusinessException;
import com.example.entity.emp.SysPermission;
import com.example.mapper.emp.SysPermissionMapper;
import com.example.service.SysPermissionService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@RequiredArgsConstructor
public class SysPermissionServiceImpl extends ServiceImpl<SysPermissionMapper, SysPermission> implements SysPermissionService {

    @Override
    public List<SysPermission> getPermissionTree() {
        return baseMapper.selectPermissionTree();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(SysPermission permission) {
        // 检查权限标识是否重复
        if (permission.getPermissionCode() != null) {
            long count = count(new LambdaQueryWrapper<SysPermission>()
                    .eq(SysPermission::getPermissionCode, permission.getPermissionCode()));
            
            if (count > 0) {
                throw new BusinessException("权限标识已存在");
            }
        }
        
        // 设置默认值
        permission.setStatus(1);
        if (permission.getSort() == null) {
            permission.setSort(0);
        }
        
        save(permission);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(SysPermission permission) {
        // 检查权限标识是否重复
        if (permission.getPermissionCode() != null) {
            long count = count(new LambdaQueryWrapper<SysPermission>()
                    .eq(SysPermission::getPermissionCode, permission.getPermissionCode())
                    .ne(SysPermission::getId, permission.getId()));
            
            if (count > 0) {
                throw new BusinessException("权限标识已存在");
            }
        }
        
        updateById(permission);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        // 检查是否有子权限
        Integer count = baseMapper.hasChildren(id);
        if (count > 0) {
            throw new BusinessException("请先删除子权限");
        }
        
        removeById(id);
    }

    @Override
    public List<Long> getRolePermissionIds(Long roleId) {
        return baseMapper.selectPermissionIdsByRoleId(roleId);
    }

    @Override
    public List<SysPermission> getUserPermissions(Long userId) {
        return baseMapper.selectPermissionsByUserId(userId);
    }
} 